package com.lqian.demo02.utils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;

/**
 * 存储连接给线程去用的管理对象工具包
 * @author：Melody_LQ
 * @time：2022/7/14 11:52 上午
 */
public class CollectionManager {
    private static ThreadLocal<Connection> localConnection = new ThreadLocal<>();

    //获取连接
    public static Connection getConnection(){
        Connection connection = localConnection.get();
        //如果容器中没有，就从连接池获取一个连接存储到ThreadLocal中
        if (connection == null){
           connection =  DruidPool.getConnection();
            localConnection.set(connection);
        }
        return connection;
    }

    //开启事务设置为手动提交
    public static void begin(){
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //事务提交
    public static void commit(){
        try {
            getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //事务回滚
    public static void rollback(){
        try {
            getConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭连接
    public static void close(){
        try {
            getConnection().close();
            //为确保连接使用过后不再被调用，需要删除此连接
            localConnection.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
